import random
import re

from flask import request, jsonify, current_app, session, abort, make_response

from info import rs, constants, db
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue


@passport_blue.route('/logout', methods=["GET", "POST"])
def logout():
    try:
        session.pop("user_id", None)
        session.pop("nick_name", None)
        session.pop("is_admin", None)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="登出失败")
    if request.method == "POST":
        return jsonify(errno=RET.OK, errmsg="登出成功")
    else:
        return "OK"


@passport_blue.route('/login', methods=["POST"])
def login():
    # 获取参数
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    if not all([password, mobile]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not user or not user.check_password(password):
        return jsonify(errno=RET.NODATA, errmsg="用户名或密码错误")

    # 设置登录session
    try:
        session["nick_name"] = user.nick_name
        session["user_id"] = user.id
        session["avatar_url"] = user.avatar_url
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="设置session失败")
    return jsonify(errno=RET.OK, errmsg="登录成功")


@passport_blue.route('/register', methods=["GET", "POST"])
def register():
    """实现注册功能"""
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    sms_code = request.json.get("sms_code")
    if not all([sms_code, mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not re.match(r"1[3456789][0-9]{9}", mobile):  # 验证手机号码规则
        return jsonify(errno=RET.PARAMERR, errmsg="手机格式有误")

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg="用户已存在")
    try:
        real_sms_code = rs.get("sms_code_" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if real_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证错误")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    try:
        session["nick_name"] = mobile
        session["user_id"] = user.id
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="自动登录失败")
    return jsonify(errno=RET.OK, errmsg="注册并自动登录成功")


@passport_blue.route('/sms_code', methods=["GET", "POST"])
def sms_code():
    """点击获取短信验证码时的反应"""
    image_code = request.json.get("image_code")
    image_code_id = request.json.get("image_code_id")
    mobile = request.json.get("mobile")

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not re.match(r"1[3456789][0-9]{9}", mobile):  # 验证手机号码规则
        return jsonify(errno=RET.PARAMERR, errmsg="手机格式有误")

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户已存在")

    try:
        real_image_code = rs.get("image_code_id_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if not real_image_code:
        return jsonify(errno=RET.DBERR, errmsg="验证码已过期")

    if real_image_code != image_code:
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")

    # 发送短信验证码(假装发送)
    sms_code_str = "%06d" % random.randint(0, 999999)
    print(sms_code_str)
    try:
        rs.setex("sms_code_" + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code_str)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    return jsonify(errno=RET.OK, errmsg="短信验证码发送成功")


@passport_blue.route('/image_code')
def image_code():
    # 图片验证码,参数
    image_code_id = request.args.get("image_code_id")
    if not image_code_id:
        return abort(403)

    # 尝试生成图片
    name, text, image_data = captcha.generate_captcha()

    # 保存到redis中
    try:
        rs.setex("image_code_id_" + image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)

    print(text)
    response = make_response(image_data)
    response.headers["Content_Type"] = "image/jpg"

    return response
